package com.regentsoft.cloudback.enterpriseAdmin.controller;

import com.regentsoft.cloudback.enterpriseAdmin.entity.MediaFile;
import com.regentsoft.cloudback.enterpriseAdmin.entity.ScreenMedia;
import com.regentsoft.cloudback.enterpriseAdmin.service.CompanyInfoService;
import com.regentsoft.cloudback.enterpriseAdmin.service.ExtraScreenService;
import com.regentsoft.cloudback.enterpriseAdmin.vo.ResultResp;
import com.regentsoft.cloudback.enterpriseAdmin.vo.req.MediaDeleteReq;
import com.regentsoft.cloudback.enterpriseAdmin.vo.req.MediaDownLoadReq;
import com.regentsoft.cloudback.enterpriseAdmin.vo.req.MediaQueryReq;
import com.regentsoft.cloudback.enterpriseAdmin.vo.req.MediaUploadReq;
import com.regentsoft.cloudback.exception.FileManagerException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 副屏
 * Created by work on 2017/11/28.
 *
 * @author lumr
 */
@RestController
@RequestMapping(value = "api/screen/")
public class ExtraScreenController {
    private final ExtraScreenService screenService;

    private final CompanyInfoService companyInfoService;

    @Autowired
    public ExtraScreenController(ExtraScreenService screenService, CompanyInfoService companyInfoService) {
        this.screenService = screenService;
        this.companyInfoService = companyInfoService;
    }

    @RequestMapping(value = "getMediaInfo", method = RequestMethod.POST)
    @ApiOperation(value = "获取媒体文件信息", response = ScreenMedia.class, httpMethod = "POST")
    public ResultResp<List<ScreenMedia>> getMediaQty(@RequestParam("REGENTTOKEN") String token, @RequestBody MediaQueryReq queryReq, HttpServletRequest request) {
        final String baseUrl = request.getRequestURL().toString().replaceAll("getMediaInfo", "downloadResource").concat("?REGENTTOKEN=").concat(token);
        final String companyId = queryReq.getCompanyId();
        if (!companyInfoService.checkCompany(companyId))
            return new ResultResp<>("企业不存在");

        List<ScreenMedia> mediaList = screenService.getScreenMedias(queryReq);
        mediaList.forEach(screenMedia -> {
            screenMedia.setCompanyId(companyId);
            screenMedia.setDownloadUrl(baseUrl);
        });
        return new ResultResp<>(mediaList);
    }

    @RequestMapping(value = "download", method = RequestMethod.POST)
    @ApiOperation(value = "下载媒体文件", response = Byte[].class, httpMethod = "POST")
    public void download(@RequestParam("REGENTTOKEN") String token, @RequestBody MediaDownLoadReq downLoadReq, HttpServletResponse response) {
        if (!companyInfoService.checkCompany(downLoadReq.getCompanyId()))
            return;

        MediaFile file = screenService.downloadMedia(downLoadReq);
        response.setContentType("application/force-download");
        response.setContentLengthLong(file.getLength());
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getFileName());
        try (OutputStream os = response.getOutputStream()) {
            if (file.getBytes() != null)
                os.write(file.getBytes());
            else {
                StreamUtils.copy(file.getInputStream(), os);
                file.getInputStream().close();
            }
        } catch (IOException e) {
            throw new FileManagerException("返回文件时失败：" + e.getMessage(), e);
        }
    }

    @RequestMapping(value = "downloadResource", method = RequestMethod.GET)
    @ApiOperation(value = "下载媒体文件", response = Byte[].class, httpMethod = "GET")
    public void downloadTest(@RequestParam("REGENTTOKEN") String token, @RequestParam("companyId") String companyId, @RequestParam("fileName") String fileName, HttpServletResponse response) {
        MediaFile file = screenService.downloadMedia(companyId, fileName);
        response.setContentType("application/force-download");
        response.setContentLengthLong(file.getLength());
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getFileName());
        try (OutputStream os = response.getOutputStream()) {
            StreamUtils.copy(file.getInputStream(), os);
            file.getInputStream().close();
        } catch (IOException e) {
            throw new FileManagerException("返回文件时失败：" + e.getMessage(), e);
        }
    }

    //    @RequestMapping(value = "uploadByPost", method = RequestMethod.POST)
//    @ApiOperation(value = "上传媒体文件(json)", response = ResultResp.class, httpMethod = "POST")
    public ResultResp upload(@RequestParam("REGENTTOKEN") String token, @RequestBody MediaUploadReq uploadReq) {

        boolean result = screenService.updateMedia(uploadReq, null);
        if (!result)
            return new ResultResp("保存文件失败。");

        return ResultResp.SUCCESS;
    }

    @RequestMapping(value = "uploadByGet", method = RequestMethod.POST)
    @ApiOperation(value = "上传媒体文件(参数)", response = ResultResp.class, httpMethod = "POST")
    public ResultResp upload1(@RequestParam("REGENTTOKEN") String token, MediaUploadReq uploadReq) {

        boolean result = screenService.updateMedia(uploadReq, uploadReq.getFile());
        if (!result)
            return new ResultResp("保存文件失败。");

        return ResultResp.SUCCESS;
    }

    @ApiOperation(value = "删除媒体文件", response = ResultResp.class, httpMethod = "POST")
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public ResultResp delete(@RequestParam("REGENTTOKEN") String token, @RequestBody MediaDeleteReq deleteReq) {

        boolean result = screenService.deleteMedia(deleteReq);
        if (!result)
            return new ResultResp("删除文件失败。");

        return ResultResp.SUCCESS;
    }

    @ApiOperation(value = "获取媒体文件url", response = ScreenMedia.class, httpMethod = "POST")
    @RequestMapping(value = "getMediaUrl", method = RequestMethod.POST)
    public ResultResp<List<ScreenMedia>> getMediaUrl(@RequestParam("REGENTTOKEN") String token, @RequestBody MediaQueryReq req, HttpServletRequest request) {

        final String companyId = req.getCompanyId();
        final String baseUrl = request.getRequestURL().toString().replaceAll("api/screen/getMediaUrl", "");
        System.out.println(request.getContextPath());
        List<ScreenMedia> mediaList = screenService.getScreenMedias(req);
        mediaList.forEach(media -> {
            media.setCompanyId(companyId);
            media.setViewUrl(baseUrl.concat(screenService.getMediaUrl(media)));
        });

        return new ResultResp<>(mediaList);
    }
}
